package com.ruoyi.jetLinks.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpClient4Utils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jetLinks.domain.DeviceType;
import com.ruoyi.jetLinks.service.IDeviceTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品分类Controller
 * 
 * @author lxx
 * @date 2022-01-27
 */
@Api(tags = "产品分类")
@RestController
@RequestMapping("/jetLinks/deviceType")
public class DeviceTypeController extends BaseController {
    @Autowired
    private IDeviceTypeService deviceTypeService;

    /**
     * 查询产品分类列表
     */
    @ApiOperation("查询产品分类列表")
    @PreAuthorize("@ss.hasPermi('jetLinks:deviceType:list')")
    @GetMapping("/list")
    public AjaxResult list(DeviceType deviceType) {
        //insertVo();
        List<DeviceType> list = deviceTypeService.selectDeviceTypeList(deviceType);
        return AjaxResult.success(list);
    }
    public void insertVo(){
        Map<String,String> requestHeadMap = new HashMap<>();
        requestHeadMap.put("Accept","application/json;charset=UTF-8");
        requestHeadMap.put("Connection","keep-alive");
        requestHeadMap.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");
        requestHeadMap.put("X-Access-Token","46d8232b1a6b016a449bb0535686e51a");
        String url = "http://demo.jetlinks.cn/jetlinks/device/category/_tree?paging=false&sorts%5B0%5D.name=id&sorts%5B0%5D.order=desc";
        String result = HttpClient4Utils.doGet(url,requestHeadMap);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray datas = jsonObject.getJSONArray("result");
        System.out.println(datas.size());
        for(int i=0;i<datas.size();i++){
            DeviceType deviceType1 = new DeviceType();
            JSONObject jsonObject1 = datas.getJSONObject(i);
            deviceType1.setRemarks(jsonObject1.getString("description"));
            deviceType1.setPath(jsonObject1.getString("path"));
            deviceType1.setDeviceKey(jsonObject1.getString("key"));
            try{
                deviceType1.setDeviceName(new String(jsonObject1.getString("name").getBytes(),"UTF-8"));
            }catch (Exception e){

            }
            deviceType1.setOrderNum(jsonObject1.getInteger("sortIndex"));
            String parentIds = jsonObject1.getString("parentId");
            if(StringUtils.isNotNull(parentIds)){
                String[] parentId = jsonObject1.getString("parentId").split("|");
                deviceType1.setParentid(Long.decode(parentId[parentId.length-2]));
            }else{
                deviceType1.setParentid(0L);
            }
            String[] id = jsonObject1.getString("id").split("|");
        //    deviceType1.setId(Long.decode(id[id.length-2]));
            deviceTypeService.insertDeviceType(deviceType1);
            System.out.println(deviceType1.getId());
            if(StringUtils.isNotNull(jsonObject1.getJSONArray("children"))){
                insertVo(deviceType1.getId(),jsonObject1.getJSONArray("children"));
            }
        }
    }
    public void insertVo(Long parentId2,JSONArray jsonArray){
        for(int i=0;i<jsonArray.size();i++){
            DeviceType deviceType1 = new DeviceType();
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            deviceType1.setRemarks(jsonObject1.getString("description"));
            deviceType1.setPath(jsonObject1.getString("path"));
            deviceType1.setDeviceKey(jsonObject1.getString("key"));
            deviceType1.setDeviceName(jsonObject1.getString("name"));
            deviceType1.setOrderNum(jsonObject1.getInteger("sortIndex"));
            deviceType1.setParentid(parentId2);
            deviceTypeService.insertDeviceType(deviceType1);
            if(StringUtils.isNotNull(jsonObject1.getJSONArray("children"))){
                insertVo(deviceType1.getId(),jsonObject1.getJSONArray("children"));
            }
        }
    }

    /**
     * 导出产品分类列表
     */
    @ApiOperation("导出产品分类列表")
    @PreAuthorize("@ss.hasPermi('jetLinks:deviceType:export')")
    @Log(title = "产品分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceType deviceType)
    {
        List<DeviceType> list = deviceTypeService.selectDeviceTypeList(deviceType);
        ExcelUtil<DeviceType> util = new ExcelUtil<DeviceType>(DeviceType.class);
        util.exportExcel(response, list, "产品分类数据");
    }

    /**
     * 获取产品分类详细信息
     */
    @ApiOperation("获取产品分类详细信息")
    @PreAuthorize("@ss.hasPermi('jetLinks:deviceType:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(deviceTypeService.selectDeviceTypeById(id));
    }

    /**
     * 新增产品分类
     */
    @ApiOperation("新增产品分类")
    @PreAuthorize("@ss.hasPermi('jetLinks:deviceType:add')")
    @Log(title = "产品分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceType deviceType) {
        return toAjax(deviceTypeService.insertDeviceType(deviceType));
    }

    /**
     * 修改产品分类
     */
    @ApiOperation("修改产品分类")
    @PreAuthorize("@ss.hasPermi('jetLinks:deviceType:edit')")
    @Log(title = "产品分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceType deviceType) {
        return toAjax(deviceTypeService.updateDeviceType(deviceType));
    }

    /**
     * 删除产品分类
     */
    @ApiOperation("删除产品分类")
    @PreAuthorize("@ss.hasPermi('jetLinks:deviceType:remove')")
    @Log(title = "产品分类", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(deviceTypeService.deleteDeviceTypeByIds(ids));
    }

    /**
     * 获取菜单下拉树列表
     */
    @ApiOperation("获取产品分类下拉树列表")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(DeviceType deviceType) {
        List<DeviceType> list = deviceTypeService.selectDeviceTypeList(deviceType);
        return AjaxResult.success(deviceTypeService.buildDeviceTypeMenuTree(list));
    }
}
